<?php

namespace App\Observers;

use App\Models\Category;
use DB;

class CategoryObserver
{
    public function created(Category $category)
    {
        $parent = $category->parent;
        DB::table('categories')->where('id', $category->id)->update([
            'path' => ($parent ? $parent->path : 0) . '-' . $category->id
        ]);
    }

    public function updating(Category $category)
    {
        //修改栏目PATH
        $parent = $category->parent;
        $category['path'] = ($parent ? $parent->path : 0) . '-' . $category->id;
        //修改子栏目PATH
        $category->childrens->map(function ($child) use ($category) {
            DB::table('categories')->where('id', $child['id'])->update([
                'path' => preg_replace('/.+\-' . $category->id . '\-/', $category->path . '-', $child['path'])
            ]);
        });
    }

    public function deleted(Category $category)
    {
        //删除所有子栏目
        $childrens = $category->childrens;
        foreach ($childrens as $key => $item) {
            DB::table('categories')->where('id', $item->id)->delete();
        }
    }

}
